﻿using System;
using System.Collections.Generic;
using static System.Runtime.InteropServices.JavaScript.JSType;
namespace ConsoleApp9;
public class TaskScheduler
{
    public static DateTime GetLastMonthDayExecutionTime(DateTime currentTime, List<int> monthDays, TimeSpan executionTime)
    {
        int currentDay = currentTime.Day;
        bool hasExecuteToday = currentTime.TimeOfDay >= executionTime;
        DateTime lastExecutionTime = DateTime.Now.AddDays(-20);
        if (!hasExecuteToday || (hasExecuteToday && !monthDays.Contains(currentDay)))
        {
            for (int i = 1; i <= 31; i++)
            {
                lastExecutionTime = currentTime.AddDays(-i).Date.Add(executionTime);
                var day = (int)lastExecutionTime.Day;
                if (monthDays.Contains(day))
                {
                    break;
                }
            }
            return lastExecutionTime;
        }
        if (monthDays.Contains(currentDay))
        {
            lastExecutionTime = currentTime.Date.Add(executionTime);
        }
        return lastExecutionTime;
    }

    public static DateTime GetLastWeeklyExecutionTime(DateTime currentTime, List<int> weeklyDays, TimeSpan executionTime)
    {
        int currentDay = (int)currentTime.DayOfWeek;
        if (currentDay == 0) currentDay = 7;
        bool hasExecuteToday = currentTime.TimeOfDay >= executionTime;
        DateTime lastExecutionTime = DateTime.Now.AddDays(-20);
        if (!hasExecuteToday || (hasExecuteToday && !weeklyDays.Contains(currentDay)))
        {
            for (int i = 1; i <= 7; i++)
            {
                lastExecutionTime = currentTime.AddDays(-i).Date.Add(executionTime);
                var week = (int)lastExecutionTime.DayOfWeek;
                if (week == 0)
                {
                    week = 7;
                }
                if (weeklyDays.Contains(week))
                {
                    break;
                }
            }
            return lastExecutionTime;
        }
        if (weeklyDays.Contains(currentDay))
        {
            lastExecutionTime = currentTime.Date.Add(executionTime);
        }
        return lastExecutionTime;
    }

    public static DateTime GetLastDayExecutionTime(DateTime currentTime, TimeSpan executionTime)
    {
        int currentDay = (int)currentTime.DayOfWeek;
        if (currentDay == 0) currentDay = 7;
        bool hasExecuteToday = currentTime.TimeOfDay >= executionTime;
        DateTime lastExecutionTime = DateTime.Now.AddDays(-20);
        if (hasExecuteToday)
        {
            lastExecutionTime = currentTime.Date.Add(executionTime);
            return lastExecutionTime;
        }
        lastExecutionTime = currentTime.Date.AddDays(-1).Add(executionTime);
        return lastExecutionTime;
    }
}